package com.vanysoft.business.index.service;

import com.vanysoft.business.base.user.dao.BaseUserMapper;
import com.vanysoft.business.base.user.entity.TBaseUser;
import com.vanysoft.business.index.action.demo.UserInfoDemo;
import com.vanysoft.business.index.dao.LoginMapper;
import com.vanysoft.business.index.entity.LoginUserFunction;
import com.vanysoft.business.index.entity.LoginUserinfo;
import com.vanysoft.common.utils.desc.DescUtil;
import com.vanysoft.common.utils.string.StringUtil;
import com.vanysoft.framework.config.file.FileProperties;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.utils.file.Base64ImageUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional(readOnly = true)
@Deprecated
public class IndexService {

    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private BaseUserMapper baseUserMapper;

    @Autowired
    private FileProperties fileProperties;//可扩展其他路径

    /**
     * Function Name               queryIndexMenuAndUserinfo
     *
     * @param userId
     * @return
     * @throws VanySoftBaseException
     * @description 根据用户代码查询展示菜单功能权限
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月19日 下午5:05:47          SharpClaw_x                     Initial
     * *********************************************************************
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public Map<String, Object> queryIndexMenuAndUserinfo(String userId) throws VanySoftBaseException {
        Map<String, Object> resultMap = new HashMap();

        // 查询用户基础信息
        LoginUserinfo baseUserinfo = loginMapper.selectUserInfoByUserId(userId);
        resultMap.put("userInfo", baseUserinfo);

        // 查询用户是否是administrator
        int adminFlag = loginMapper.checkAdminByUserId(userId);

        // 查询用户的所有菜单
        if (adminFlag == 0) {
            List<Map<String, Object>> menuCodeList = loginMapper.queryUserMenuTreeCodes(userId);
            List<String> menuCodeArray = new ArrayList<>();
            if (null != menuCodeList) {
                Set<String> menuCodeSet = new HashSet<String>();
                for (Map<String, Object> itemMap : menuCodeList) {
                    if (null != itemMap.get("functionCode")) {
                        String functionCodes = String.valueOf(itemMap.get("functionCode"));
                        String[] functionCodeArr = functionCodes.split(",");
                        for (String functionCode : functionCodeArr) {
                            menuCodeSet.add(functionCode);
                        }
                    }
                }
                if (menuCodeSet.size() > 0) {
                    menuCodeArray.addAll(menuCodeSet);
                }
            }
            if (menuCodeArray.size() > 0) {
                List<Map<String, Object>> menuListMap = loginMapper.queryMenuByCodes(menuCodeArray);
                List<Map<String, Object>> menuTreeMap = StringUtil.listToTree(menuListMap, "functionCode", "parentfunctionCode", "childrenList");
                resultMap.put("menuTree", menuTreeMap);
            }
        } else {
            List<Map<String, Object>> menuListMap = loginMapper.queryAllMenu();
            List<Map<String, Object>> menuTreeMap = StringUtil.listToTree(menuListMap, "functionCode", "parentfunctionCode", "childrenList");
            resultMap.put("menuTree", menuTreeMap);
        }


        // 查询用户的所有权限
        List<LoginUserFunction> userFunctionList = null;
        if (adminFlag == 0) {
            userFunctionList = loginMapper.queryUserBaseAPI(userId);
        } else {
            userFunctionList = loginMapper.queryAllAPI();
        }
        List<Map<String, String>> permissionList = new ArrayList<>();
        for (LoginUserFunction item : userFunctionList) {
            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("functionCode", item.getFunctionCode() == null ? null : item.getFunctionCode());
            itemMap.put("id", item.getApiId() == null ? null : item.getApiId());
            itemMap.put("name", item.getApiName() == null ? null : item.getApiName());
            itemMap.put("value", item.getApiURI() == null ? null : item.getApiURI());
            permissionList.add(itemMap);
        }
        resultMap.put("functionList", permissionList);

        return resultMap;
    }


    /**
     * Function Name               queryUserinfo
     *
     * @param userId
     * @return
     * @description TODO(根据用户代码查询用户所有信息)
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月22日 下午8:50:43          SharpClaw_x                     Initial
     * *********************************************************************
     */
    public Map<String, Object> queryUserinfo(String userId) {
        Map<String, Object> map = new HashMap<String, Object>();

        //人员信息
        LoginUserinfo tBaseUser = loginMapper.selectUserInfoByUserId(userId);

        // 组织机构信息
        List<Map<String, Object>> orgList = loginMapper.queryUserOrgList(userId);
        // 群组
        List<Map<String, Object>> teamList = loginMapper.queryUserTeamList(userId);
        // 分类
        List<Map<String, Object>> tagList = loginMapper.queryUserTagList(userId);

        map.put("userInfo", tBaseUser);
        map.put("orgInfo", orgList);
        map.put("teamInfo", teamList);
        map.put("tagInfo", tagList);

        return map;
    }

    /**
     * Function Name               updateUserInfo
     *
     * @param userInfoDemo
     * @throws VanySoftBaseException
     * @description 更新当前用户的基础信息
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月15日 上午10:39:52           SharpClaw_x                     Initial
     * *********************************************************************
     */
    @Transactional
    public void updateUserInfo(UserInfoDemo userInfoDemo) throws VanySoftBaseException {
        TBaseUser entity = new TBaseUser();
        BeanUtils.copyProperties(userInfoDemo, entity);

        String bgImg = userInfoDemo.getPhoto();
        if (StringUtils.isNotBlank(bgImg)) {
            bgImg = bgImg.substring(4, bgImg.length() - 1);
            String appIconPathHead = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            String appIconPathBody = fileProperties.getUserHeadImgBasePath() + userInfoDemo.getUserId() + ".jpg";
            Base64ImageUtil.generateImage(bgImg, appIconPathHead + appIconPathBody);
            entity.setPhotoUrl(appIconPathBody);
        }

        int updateFlag = baseUserMapper.updateByPrimaryKeySelective(entity);
        if (0 == updateFlag) {
            throw new VanySoftBaseException(MessageCodeConstant.RTN_CODE_UPDATE_FAIL);
        }
    }

    /**
     * Function Name               updateUserPassword
     *
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     * @description TODO(修改密码)
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月23日 下午9:05:50          SharpClaw_x                     Initial
     * *********************************************************************
     */
    @Transactional
    public String updateUserPassword(String userId, String oldPassword, String newPassword) {
        // 测试
        TBaseUser tBaseUser = baseUserMapper.selectByPrimaryKey(userId);

        if (!StringUtils.equals(DescUtil.encrypt(oldPassword), tBaseUser.getUserPassword())) {
            // 原始密码输入错误
            return MessageCodeConstant.UserException.RTN_CODE_ORIGINAL_PASSWORD_ERROR;
        } else if (StringUtils.equals(DescUtil.encrypt(newPassword), tBaseUser.getUserPassword())) {
            // 新密码不能与原始密码重复
            return MessageCodeConstant.UserException.RTN_CODE_PASSWORD_REPEAT;
        } else {
            TBaseUser tuser = new TBaseUser();
            tuser.setUserId(userId);
            tuser.setUserPassword(DescUtil.encrypt(newPassword));
            int r = baseUserMapper.updateByPrimaryKeySelective(tuser);
            if (r > 0) {
                // 修改成功
                return MessageCodeConstant.RTN_CODE_SUCCESS;
            } else {
                // 修改失败
                return MessageCodeConstant.UserException.RTN_CODE_UPDATE_FAIL;
            }
        }
    }
}
